<template>
  <div>
    <el-row>
      <el-col :span="6" style="padding: 20px 20px 0px">
        <el-card>
          <div slot="header" class="clearfix">
            <span>在线用户</span>
          </div>
          <div v-if="showOnlineUsers">
            <template v-for="user in onlineUsers">
              <el-button
                v-if="user.userId !== id"
                :key="user.userId"
                style="width: 100%"
                @click="changeRoomTitle(user.userId, 'user', user)"
              >
                {{ user.username }}
                <span v-if="user.unreadMessages > 0" class="unread-badge">{{
                  user.unreadMessages
                }}</span>
              </el-button>
            </template>
          </div>
          <div v-else>
            <p>暂无用户信息</p>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12" style="padding: 20px 0px 0px; height: 50%">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ roomTitle }}</span>
          </div>
          <div class="messages">
            <div
              v-for="(message, index) in filteredMessages"
              :key="index"
              :class="{
                'my-message': message.from === userID,
                'other-message': message.from !== userID,
              }"
            >
              <div class="message-bubble">{{ message.content }}</div>
            </div>
          </div>
          <el-input
            v-model="inputMessage"
            placeholder="输入消息"
            @keyup.enter.native="sendMessageToUser(roomTitle)"
          ></el-input>
          <el-button type="primary" @click="sendMessageToUser(roomTitle)"
            >发送</el-button
          >
        </el-card>
      </el-col>

      <el-col :span="6" style="padding: 20px 20px 0px">
        <el-card>
          <!-- 创建群聊的模态框 -->
          <el-dialog :visible.sync="showCreateGroupModal" title="创建群聊">
            <el-form
              ref="createGroupForm"
              :model="createForm"
              label-width="80px"
            >
              <el-form-item label="群聊名称" prop="groupName">
                <el-input
                  v-model="createForm.groupName"
                  placeholder="请输入群聊名称"
                ></el-input>
              </el-form-item>
              <!-- 在这里添加其他群聊相关的表单项，如成员选择等 -->
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showCreateGroupModal = false">取消</el-button>
            </span>
          </el-dialog>
          <!-- 聊天室列表 -->
          <div v-if="message.roomList.length > 0">
            <el-card v-for="room in message.roomList" :key="room.roomId">
              <div slot="header" class="clearfix">
                <span>{{ room.roomId }}</span>
                <el-button
                  type="text"
                  style="float: right; padding: 3px 0"
                  @click="enterRoom(room.roomId)"
                >
                  进入
                </el-button>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getInfo } from "../../../api/login";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      showCreateGroupModal: false, // 控制创建群聊模态框的显示
      createForm: {
        // 创建群聊表单数据
        groupName: "", // 群聊名称
        // 其他群聊相关的字段
      },
      userID: null,
      ws: null,
      isGroup: "0",
      messages: [],
      onlineUsers: [],
      inputMessage: "",
      roomTitle: "聊天室",
      roomList: [],
      roomId: 1,
      roomName: null,
      message: { roomList: [] }, // 定义 message 并包含 roomList 属性
    };
  },
  computed: {
    ...mapGetters({
      id: "userId",
    }),
    showOnlineUsers() {
      return this.onlineUsers.length > 0;
    },
    filteredMessages() {
      const filtered = this.messages.filter(
        (message) =>
          (message.to === this.roomTitle && message.from === this.userID) ||
          message.from === this.roomTitle ||
          message.to === this.userID
      );

      console.log("Filtered messages:", filtered);
      return filtered;
    },
  },
  methods: {
    async getUserID() {
      try {
        const response = await getInfo();
        this.userID = response.user.userId;
        return this.userID;
      } catch (error) {
        console.error("获取用户信息时出错:", error);
        throw error;
      }
    },
    //连接websocket用户展示
    async connectWebSocket() {
      const userID = await this.getUserID();
      this.ws = new WebSocket(
        "ws://127.0.0.1:8080/websocket/message/" + userID
      );
      // this.ws = new WebSocket("ws://127.0.0.1:8080/websocket/message/");
      this.ws.onopen = () => {
        console.log("WebSocket connected");
      };

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        console.log("Received WebSocket message:", message);

        if (message.onlineUsers) {
          this.$set(
            this,
            "onlineUsers",
            message.onlineUsers.map((user) => ({
              ...user,
              unreadMessages: 0,
            }))
          );
          console.log("Updated online users:", this.onlineUsers);
        } else if (message.roomList) {
          this.$set(this.message, "roomList", message.roomList);
        } else {
          this.$set(this.messages, this.messages.length, {
            from: message.from,
            to: message.to,
            content: message.content,
          });

          console.log(
            "接收到消息：",
            message.content,
            "来自用户：",
            message.from,
            "发送给用户：",
            message.to
          );
          if (message.to === this.userID) {
            const userIndex = this.onlineUsers.findIndex(
              (user) => user.userId === message.from
            );
            if (userIndex !== -1) {
              this.$set(this.onlineUsers, userIndex, {
                ...this.onlineUsers[userIndex],
                unreadMessages: this.onlineUsers[userIndex].unreadMessages + 1,
              });
            }
          }
        }
      };

      this.ws.onclose = () => {
        console.log("WebSocket disconnected");
      };

      this.ws.onerror = (error) => {
        console.error("WebSocket error", error);
      };
    },
    sendMessageToUser(userId) {
      debugger;
      if (this.inputMessage.trim() !== "") {
        // 直接获取最新的 isGroup 值
        const isGroup = this.isGroup;
        // 判断是否为群聊，如果是，则将接收方设置为 roomId，否则保持原样
        const to = isGroup === "1" ? this.roomId : userId;
        const message = {
          isGroup: isGroup,
          to: to,
          from: this.userID,
          content: this.inputMessage,
        };
        const string = JSON.stringify(message);
        this.ws.send(string);
        this.messages.push({
          from: this.userID,
          to: userId,
          content: this.inputMessage,
        });
        console.log("发送消息：", this.inputMessage, "给用户：", userId);
        this.inputMessage = "";
      }
    },
    changeRoomTitle(name, type, user) {
      if (type === "user") {
        // 单聊
        this.isGroup = "0";
        this.roomTitle = name; // 设置为用户名
        const userIndex = this.onlineUsers.findIndex(
          (u) => u.userId === user.userId
        );
        if (userIndex !== -1) {
          this.$set(this.onlineUsers, userIndex, {
            ...user,
            unreadMessages: 0,
          });
        }
      } else if (type === "group") {
        // 群聊
        this.isGroup = "1";
        const room = this.message.roomList.find(
          (room) => room.roomName === name
        );

        if (room) {
          this.roomTitle = room.roomId; // 设置为roomId
          console.log("群聊ID---", this.roomTitle);
        } else {
          console.error("未找到对应的群聊");
        }
      }
      console.log("Changed room title to:", this.roomTitle);
    },

    // 进入聊天室
    enterRoom(roomId) {
      this.isGroup = "1";
      console.log("更新的", this.isGroup);
      // 向后端发送消息，告知用户加入了指定的聊天室,但是后端不知道啊，卓越班
      const message = {
        joinGroup: roomId,
        userId: this.userID,
      };
      // 查找对应的聊天室名称
      // const room = this.message.roomList.find((room) => room.roomId === roomId);
      // if (room) {
      //   this.roomTitle = room.roomName;
      //   console.log("聊天室名称---", this.roomTitle);
      // } else {
      //   console.error("未找到对应的聊天室");
      // }

      this.ws.send(JSON.stringify(message));

      console.log("进入聊天室：", roomId);
    },
    // // 创建群聊
    // createGroup() {
    //   // 发送创建群聊请求给后端服务器，传递 this.createForm 中的数据
    //   // 处理创建群聊成功或失败的逻辑
    //   // 关闭创建群聊模态框
    //   this.showCreateGroupModal = false;
    // },
  },
  watch: {
    "message.roomList"(newVal, oldVal) {
      console.log("Room list updated:", newVal);
    },
  },
  mounted() {
    this.connectWebSocket();
    console.log("Initial room list:", this.message.roomList);
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
  },
};
</script>

<style scoped>
.chat-room {
  max-width: 600px;
  margin: 50px auto;
}

.messages {
  height: 400px;
  /* 设置对话框容器的高度 */
  max-height: 50%;
  overflow-y: auto;
  margin-bottom: 20px;
}

.my-message {
  text-align: right;
}

.other-message {
  text-align: left;
}

.message-bubble {
  display: inline-block;
  background-color: #e0e0e0;
  padding: 5px 10px;
  border-radius: 10px;
  margin: 5px;
}

.unread-badge {
  background-color: red;
  color: white;
  padding: 3px 6px;
  border-radius: 50%;
  font-size: 12px;
  margin-left: 5px;
}

.message {
  margin: 5px 0;
}
</style>
